require([
  'jquery',
  'pageInit',
  'dataTableFilter',
  'loading',
  'listAsyncOp'
], function($, vamakerPage, VamDataTable, VamLoader, VamListOp) {
  $(function() {
    var 
      $dataTable = $('#data-table'),
      dataUrl = VAM.getVar('ADS_LIST_DATA_LIST'),
      dataPackOp = VAM.getVar('ADS_INFO_DATA_LIST'),
      dataEidtUrl = VAM.getVar('DATA_EDIT_URL'),
      $filterFrm = $('#filter-frm'),
      $filterChannel = $filterFrm.find('input[name="filter-channel"]'),
      $filterTraffic = $filterFrm.find('input[name="filter-traffic"]'),
      $reportDataThead = $dataTable.find('thead'),
      $loadingWrap = new VamLoader().loader($('#list-loading-wrap')),
      listTable, tableOptions = {},
      adsInfoListRender;
    // Sub list render.
    adsInfoListRender = function (data) {
      // console.log(data)
      var resultStr = '',
        subArr = data;
      if (subArr.length === 0) {
        resultStr = '<tr><td colspan="2"><p class="text-center">' + VAM.j('The data in the table is empty') + '</p></td></tr>';
      } else {
        for (var i = 0; i < subArr.length; i++) {
          var subStr = '<tr>'
                     + '<td><p title="' + subArr[i].id + '">' + subArr[i].id +'</p></td>'
                     + '<td><p title="' + subArr[i].name + '">' + subArr[i].name +'</td>'
                     + '</tr>';
          resultStr += subStr;
        }
      };
      resultStr = '<table cellpadding="0" cellspacing="0" border="0" class="table table-hover table-bordered" style="margin-bottom:0;border: 1px solid #ddd;">'
                + '<thead>'
                + '<tr><th title="ID">ID</th><th title="' + VAM.j('Adspace Name') + '">' + VAM.j('Adspace Name') + '</th></tr>'
                + '</thead>'
                + '<tbody>'
                + resultStr
                + '</tbody></table>';
      return resultStr;
    };
    // Table settings.
    tableOptions = {
      'ajax': {
        'url': dataUrl
      },
      'order': [8,'desc'],
      'columns': [
        {'data': 'id'},
        {'data': 'name'},
        {'data': 'app_type'},
        {'data': 'size'},
        {'data': 'floor_price'},
        {'data': 'ceiling_price'},
        {'data': 'type'},
        {'data': 'allowFormat'},
        {'data': 'modifiedDate'},
        {'data': 'action'},
      ],
      'columnDefs': [
        {
          'targets': [0,2,4,5,6,7,8],
          'render': function (data, type, full, meta) {
            return '<p title="' + data + '">' + data + '</p>'
          }
        },
        {
          'targets': 1,
          'render': function (data, type, full, meta) {
            return '<p title="' + data + '">' + data + '<button title="' + VAM.j('View Adspace Infos') + '" class="btn btn-link btn-xs pull-right tab-ads-list" data-type="pack" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i> ' + VAM.j('loading') + '..." data-id="' + full.id + '"><i class="fa fa-plus-circle"></i></button></p>'
          }
        },
        {
          'targets': 3,
          'render': function (data, type, full, meta) {
            var sizeList = []
            for (var i = 0, len = data.length; i < len; i++) {
              if( i < 1) {
                sizeList.push('<span class="list-item">' + data[i]+ '</span>');
              } else if (i >= 1 && i < 10) {
                sizeList.push('<span class="list-item">, ' + data[i]+ '</span>')
              } else {
                sizeList.push('<span class="list-item vam-hidden">, ' + data[i]+ '</span>')
              }
            }
            if (data.length > 10) {
              return '<p>' + sizeList.join('') +'<button title="' + VAM.j('More Size') + '" class="btn btn-link btn-xs view-more-size">' + VAM.j('More') + '</button></p>';
            }
            return '<p>' + sizeList.join('') + '</p>';
          }
        },
        {
          'targets': -1,
          'render': function (data, type, full, meta) {
            return '<div class="tab-btn-group">'
                  + '<input type="hidden" class="row-info" value="' + full.id + '"/>'
                  + '<a href="' + dataEidtUrl + '?id=' + full.id + '" class="btn btn-primary btn-xs tab-edit" data-type="edit" data-loading-text="<i class=\'fa fa-spinner fa-spin\'></i>" title="' + VAM.j('Edit') + '"><i class="fa fa-edit"></i></a>'
                  + '</div>';
          }
        }
      ],
      'initComplete': function() {
        tableResize = new VamDataTable().columnResize($dataTable);
      },
    };
    $dataTable
    .on('preXhr.dt', function(evt) {
      $loadingWrap.show();
    });
    listTable = new VamDataTable().dataTables($dataTable, tableOptions);
    // After table data list.
    listTable.on('xhr.dt', function(evt) {
      $loadingWrap.fadeOut();
    });

    $dataTable.on('click', 'tbody td .tab-ads-list', function () {
      var $me = $(this),
          opId = $me.data('id'),
          opType = $me.data('type'),
          $icon = $me.find('.fa'),
          tr = $(this).parents('tr'),
          row = listTable.row(tr);
      $icon.toggleClass('fa-minus-circle');
      if (row.child.isShown()) {
        row.child.hide();
        tr.removeClass('shown');
      } else {
        VamListOp.listOp({
          url: dataPackOp,
          data: {
            id: opId,
            type: opType
          },
          before: function () {
            $me.button('loading');
          },
          success: function (data) {
            row.child(adsInfoListRender(data)).show();
            tr.addClass('shown');
          },
          always: function () {
            $me.button('reset');
          }
        });
      }
    });

    $dataTable.on('click', 'tbody td .view-more-size', function () {
      var $me = $(this),
        meTxt = $me.text(),
        $sizeList = $me.siblings('.list-item:gt(10)');
      if (meTxt === VAM.j('More')) {
        $me.text(VAM.j('Fold'));
      } else {
        $me.text(VAM.j('More'));
      }
      $sizeList.toggleClass('vam-hidden');
    });

    $filterChannel.on('change', function(evt) {
      var $me = $(this),
      meVal = $me.val(),
      column = $me.data('column');
      evt.preventDefault();
      $filterChannel.parent().removeClass('active');
      $me.parent().addClass('active');
      listTable.columns(column).search(meVal).draw();
    });
    
    $filterTraffic.on('change', function(evt) {
      var $me = $(this),
      meVal = $me.val(),
      column = $me.data('column');
      evt.preventDefault();
      $filterTraffic.parent().removeClass('active');
      $me.parent().addClass('active');
      listTable.columns(column).search(meVal).draw();
    });
  });
});
